const { app, BrowserWindow, ipcMain, screen } = require('electron');
const path = require('path');
const fs = require('fs');

let mainWindow;
let machineWindows = {};

const appState = {
  lastCommand: null
};

const stateFile = path.join(__dirname, 'app-state.json');

// 公共窗口配置
const commonWindowConfig = {
  autoHideMenuBar: true,
  minWidth: 1090,
  minHeight: 638,
  webPreferences: {
    nodeIntegration: false,
    contextIsolation: true,
    enableRemoteModule: false,
    preload: path.join(__dirname, 'preload.js'),
    webSecurity: true
  }
};

// 加载应用状态
function loadAppState() {
  try {
    console.log('状态文件路径:', stateFile);
    
    if (fs.existsSync(stateFile)) {
      const data = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
      Object.assign(appState, data);
      console.log('应用状态加载成功:', appState);
    } else {
      console.log('状态文件不存在，使用默认状态');
      saveAppState(); // 创建初始状态文件
    }
  } catch (error) {
    console.error('加载应用状态失败:', error);
  }
}

function saveAppState() {
  try {
    fs.writeFileSync(stateFile, JSON.stringify(appState, null, 2));
    console.log('应用状态已保存到:', stateFile);
  } catch (error) {
    console.error('保存应用状态失败:', error);
  }
}

function updateAppState(stateType, data) {
  appState.lastCommand = {
    type: stateType,
    data: data,
    timestamp: new Date().toISOString()
  };
  saveAppState();
}

function getDisplayConfig(isPrimary = true) {
  const displays = screen.getAllDisplays();
  const primaryDisplay = screen.getPrimaryDisplay();
  
  console.log(`检测到 ${displays.length} 个显示器`);
  
  let targetDisplay;
  if (isPrimary || displays.length === 1) {
    targetDisplay = primaryDisplay;
    console.log('使用主显示器');
  } else {
    targetDisplay = displays.find(d => d.id !== primaryDisplay.id) || primaryDisplay;
    console.log('使用外接显示器');
  }
  
  const { width, height } = targetDisplay.workAreaSize;
  const { x, y } = targetDisplay.bounds;
  
  return { x, y, width, height };
}

function setupWindowHandlers(window, windowName) {
  window.once('ready-to-show', () => {
    window.show();
    window.maximize();
    console.log(`${windowName}已设置为最大化模式`);
  });

  window.webContents.on('before-input-event', (event, input) => {
    if (input.key === 'Escape' && input.type === 'keyDown') {
      console.log(`在${windowName}检测到 ESC 键，退出应用`);
      app.quit();
    }
  });
}

function createMainWindow() {
  const iconPath = path.join(__dirname, 'public', 'app-icon.ico');
  const displayConfig = getDisplayConfig(true);
  
  mainWindow = new BrowserWindow({
    ...displayConfig,
    ...commonWindowConfig,
    show: false,
    icon: iconPath,
    title: '消息同步管理系统 - 主控制台'
  });

  setupWindowHandlers(mainWindow, '主控制台');

  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:5173');
  } else {
    mainWindow.loadFile(path.join(__dirname, 'dist/renderer/index.html'));
  }
  
  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  return mainWindow;
}

const machineNames = {
  'machine': '1号机',
  'machine2': '2号机', 
  'machine3': '3号机'
};

function createMachineWindow(machineId) {
  if (machineWindows[machineId] && !machineWindows[machineId].isDestroyed()) {
    machineWindows[machineId].focus();
    return;
  }

  const iconPath = path.join(__dirname, 'public', 'app-icon.ico');
  const displayConfig = getDisplayConfig(false);
  
  machineWindows[machineId] = new BrowserWindow({
    ...displayConfig,
    ...commonWindowConfig,
    show: false,
    icon: iconPath,
    title: `消息同步管理系统 - ${machineNames[machineId]}`
  });

  const route = `/${machineId}`;
  if (process.env.NODE_ENV === 'development') {
    machineWindows[machineId].loadURL(`http://localhost:5173#${route}`);
  } else {
    machineWindows[machineId].loadFile(path.join(__dirname, 'dist/renderer/index.html'), {
      hash: route
    });
  }
  
  setupWindowHandlers(machineWindows[machineId], machineNames[machineId]);
  
  machineWindows[machineId].webContents.on('did-finish-load', () => {
    console.log(`${machineId} 窗口加载完成`);
  });

  machineWindows[machineId].on('closed', () => {
    delete machineWindows[machineId];
  });
}

// 设置媒体权限处理
app.whenReady().then(() => {
  // 处理媒体权限请求
  const { session } = require('electron');
  
  session.defaultSession.setPermissionRequestHandler((webContents, permission, callback) => {
    console.log('权限请求:', permission);
    
    // 自动允许媒体权限
    if (permission === 'media' || permission === 'microphone') {
      callback(true);
    } else {
      callback(false);
    }
  });
  
  // 处理权限检查
  session.defaultSession.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
    console.log('权限检查:', permission, details);
    
    if (permission === 'media' || permission === 'microphone') {
      return true;
    }
    return false;
  });
  loadAppState();
  createMainWindow();
  createMachineWindow('machine');

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createMainWindow();
      createMachineWindow('machine');
    }
  });
});

// 当所有窗口都关闭时退出应用
app.on('window-all-closed', () => {
  // 保存应用状态
  saveAppState();
  
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// 应用退出前保存数据
app.on('before-quit', () => {
  saveAppState();
});

// IPC事件处理：打开机器窗口
ipcMain.handle('open-machine-window', async (event, machineId) => {
  createMachineWindow(machineId);
  return `${machineId}窗口已打开`;
});

ipcMain.handle('send-direct-message', async (event, { targetWindow, data }) => {
  try {
    updateAppState('message', data);
    
    const targetWindowInstance = targetWindow === 'main' 
      ? mainWindow 
      : machineWindows[targetWindow];
    
    if (!targetWindowInstance || targetWindowInstance.isDestroyed()) {
      console.log(`目标窗口 ${targetWindow} 不存在，状态已保存`);
      return {
        success: false,
        targetWindow,
        timestamp: new Date().toISOString(),
        message: `目标窗口 ${targetWindow} 不存在，状态已保存`,
        windowMissing: true
      };
    }
    
    targetWindowInstance.webContents.send('direct-message-received', {
      ...data,
      fromWindow: getWindowType(event.sender),
      targetWindow
    });
    
    return {
      success: true,
      targetWindow,
      timestamp: new Date().toISOString(),
      message: `消息已发送到 ${targetWindow}`
    };
  } catch (error) {
    console.error('发送点对点消息失败:', error);
    return {
      success: false,
      timestamp: new Date().toISOString(),
      error: error.message
    };
  }
});

ipcMain.handle('get-connection-status', async (event) => {
  const activeWindows = [];
  
  if (mainWindow && !mainWindow.isDestroyed()) {
    activeWindows.push('main');
  }
  
  Object.keys(machineWindows).forEach(machineId => {
    if (machineWindows[machineId] && !machineWindows[machineId].isDestroyed()) {
      activeWindows.push(machineId);
    }
  });
  
  return {
    currentWindow: getWindowType(event.sender),
    activeWindows,
    timestamp: new Date().toISOString()
  };
});

ipcMain.handle('get-app-state', async () => {
  return {
    success: true,
    data: appState
  };
});

ipcMain.handle('swap-windows', async () => {
  try {
    const machineWindow = machineWindows['machine'];
    
    // 检查窗口是否存在
    if (!mainWindow || mainWindow.isDestroyed()) {
      throw new Error('主控制台窗口不存在');
    }
    if (!machineWindow || machineWindow.isDestroyed()) {
      throw new Error('1号机窗口不存在');
    }
    
    // 获取当前窗口的位置和大小
    const mainBounds = mainWindow.getBounds();
    const machineBounds = machineWindow.getBounds();
    
    // 检查是否处于全屏状态
    const mainIsFullScreen = mainWindow.isFullScreen();
    const machineIsFullScreen = machineWindow.isFullScreen();
    
    console.log('交换前 - 主控制台:', mainBounds);
    console.log('交换前 - 1号机:', machineBounds);
    
    // 如果窗口处于全屏状态，先退出全屏
    if (mainIsFullScreen) mainWindow.setFullScreen(false);
    if (machineIsFullScreen) machineWindow.setFullScreen(false);
    
    // 交换窗口位置和大小
    mainWindow.setBounds(machineBounds);
    machineWindow.setBounds(mainBounds);
    
    // 如果之前是全屏状态，恢复全屏（交叉恢复）
    if (machineIsFullScreen) mainWindow.setFullScreen(true);
    if (mainIsFullScreen) machineWindow.setFullScreen(true);
    
    console.log('交换后 - 主控制台:', machineWindow.getBounds());
    console.log('交换后 - 1号机:', mainWindow.getBounds());
    
    return {
      success: true,
      message: '窗口位置已交换',
      timestamp: new Date().toISOString()
    };
  } catch (error) {
    console.error('窗口交换失败:', error);
    return {
      success: false,
      error: error.message,
      timestamp: new Date().toISOString()
    };
  }
});

function getWindowType(webContents) {
  if (mainWindow && mainWindow.webContents === webContents) {
    return 'main';
  }
  
  for (const [machineId, window] of Object.entries(machineWindows)) {
    if (window && window.webContents === webContents) {
      return machineId;
    }
  }
  
  return 'unknown';
}
